import cv2
import numpy
import socket
import struct
#HOST='127.0.0.1'
HOST='10.250.39.25'
PORT=9998
server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #socket对象
server.connect((HOST,PORT))
print('now starting to send frames...')
capture=cv2.VideoCapture(0) #VideoCapture对象，可获取摄像头设备的数据
capture.set(cv2.CAP_PROP_FRAME_WIDTH,640) 
capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
capture.set(cv2.CAP_PROP_FPS,30)
try:
  while True:
    success,frame=capture.read()
    k=cv2.waitKey(10)
    while not success and frame is None:
      success,frame=capture.read() #获取视频帧
    cv2.imshow("frame",frame)
    result,imgencode=cv2.imencode('.jpg',frame,[cv2.IMWRITE_JPEG_QUALITY,50]) #编码
    server.sendall(struct.pack('i',imgencode.shape[0])) #发送编码后的字节长度，这个值不是固定的
    print(imgencode.shape[0])
    server.sendall(imgencode) #发送视频帧数据
    print('have sent one frame')
except Exception as e:
  print(e)
  server.sendall(struct.pack('c',1)) #发送关闭消息
  capture.release()
  server.close()
